#!/usr/bin/env python
#
# Copyright 2010 Sebible Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""A base serializer to handle django_ldap models"""


from StringIO import StringIO

from django.core.serializers.base import Serializer as DjangoSerializer
from django.utils.encoding import smart_unicode

class Serializer(object):
    def serialize(self, queryset, **options):
        """
        Serialize a queryset.
        """
        self.options = options

        self.stream = options.get("stream", StringIO())
        self.selected_fields = options.get("fields")
        self.style = options.pop("style", 'django')

        self.start_serialization()
        for obj in queryset:
            self.start_object(obj)
            for field in obj._ldap_options.attr.keys():
                self.handle_field(obj, field)
            for field in obj._ldap_options.attr_mapping.keys():
                self.handle_field(obj, field)
            self.end_object(obj)
        self.end_serialization()
        return self.getvalue()
    
    def handle_field(self, obj, field):
        if field not in obj._ldap_options.no_serialize_fields:
            self._current[field] = getattr(obj, field)
        
    def end_object(self, obj):
        if self.style == 'simple':
            self.objects.append(self._current)
        else:
            self.objects.append({
                "model"  : smart_unicode(obj._meta),
                "pk"     : smart_unicode(obj._get_pk_val(), strings_only=True),
                "fields" : self._current
            })
        self._current = None